package ${basepackage}.controller.op;

import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.excalibur.core.util.EncryptUtils;
import com.excalibur.core.util.SpringUtils;
import com.excalibur.core.util.StringHelper;
import com.excalibur.core.util.captcha.CaptchaGenerator;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import ${basepackage}.controller.basic.DateTimeBinderController;
import ${basepackage}.model.json.JsonResponse;

@Controller
public class CommonController extends DateTimeBinderController {

	protected final static Logger logger = LoggerFactory
			.getLogger(CommonController.class);

	/**
	 * 首页.
	 * 
	 * @return
	 */
	@RequestMapping(value = { "/index", "/" })
	public String index() {
		return "redirect:login";
	}

	/**
	 * 登录页面.
	 * 
	 * @return
	 */
	@RequestMapping(value = "/login")
	public String loginform(String username, ModelMap model,
			HttpServletRequest request) {

		String shiroLoginFailure = (String) request
				.getAttribute("shiroLoginFailure");

		if (StringHelper.isNotBlank(shiroLoginFailure)) {
			model.put(
					"msg",
					SpringUtils
							.getI18nMessage("webapp.controller.CommonController.loginform.loginFailed"));
			logger.info(SpringUtils
					.getI18nMessage("webapp.controller.CommonController.loginform.loginFailed"));
		}

		model.put("username", username);

		return "login";
	}

	/**
	 * 生成验证码一次性键-值.
	 * 
	 * @param captchaType
	 * @param session
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/captcha/key")
	@ResponseBody
	public JsonResponse getCapchaKey(@RequestParam String captchaType,
			HttpSession session) {

		JsonResponse jsonResponse = new JsonResponse();
		String captchaText = CaptchaGenerator.generateCaptchaText();
		if (StringHelper.isNotBlank(captchaType)) {
			String uuidKey = EncryptUtils.getUUID();
			Map<String, String> captchaTextMap = (Map<String, String>) session
					.getAttribute(captchaType);
			if (captchaTextMap == null) {
				captchaTextMap = new HashMap<String, String>();
			}
			captchaTextMap.clear();
			captchaTextMap.put(uuidKey, captchaText);
			session.setAttribute(captchaType, captchaTextMap);
			logger.info("Generate a captcha text, and put it into session, captchakey = "
					+ captchaType);
			jsonResponse.setCode(0);
			jsonResponse.setData(uuidKey);
		} else {
			jsonResponse.setCode(1);
			jsonResponse
					.setMessage(SpringUtils
							.getI18nMessage("webapp.controller.CommonController.getCapchaKey.failed"));
		}

		return jsonResponse;
	}

	/**
	 * 验证码图片生成服务.
	 * 
	 * @param captchaType
	 * @param captchaKey
	 * @param session
	 * @param response
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/captcha/img")
	public void getCaptcha(@RequestParam String captchaType,
			@RequestParam String captchaKey, HttpSession session,
			HttpServletResponse response) {

		Map<String, String> captchaTextMap = (Map<String, String>) session
				.getAttribute(captchaType);

		if (captchaTextMap != null) {
			String captchaText = captchaTextMap.get(captchaKey);

			if (StringHelper.isNotBlank(captchaText)) {
				byte[] captchaImg = CaptchaGenerator
						.generateCaptchaImage(captchaText);

				response.setContentType(CaptchaGenerator.DEFAULT_IMAGE_MIME_TYPE);

				OutputStream os;
				try {
					os = response.getOutputStream();

					os.write(captchaImg);
					os.flush();
					os.close();
				} catch (IOException e) {
					logger.error("Generate captcha failed！", e);
				}
			}
		}
	}
}
